package comm.receive;

import com.alibaba.fastjson.JSONObject;
import comm.dataclass.RawDataDisplay;
import comm.util.BitOperator;
//import org.apache.log4j.*;
import org.apache.tomcat.util.buf.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.*;


public class ReceiveServerData implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(ReceiveServerData.class);

    JTable jTable;
    Socket cilent;
    JButton jbtSubscribe;
    JList jListMessage;

    private boolean needStop = false;

    public ReceiveServerData(JTable jTable, Socket cilent, JButton jbtSubscribe, JList jListMessage) {
        this.jTable = jTable;
        this.cilent = cilent;
        this.jbtSubscribe = jbtSubscribe;
        this.jListMessage = jListMessage;
    }

    public void stopTheRunnable() {
        needStop = true;
    }

    @Override
    public void run() {
        //System.out.print("Thread state is:" + Thread.currentThread().getState());
        if (needStop) {
            return;
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(cilent.getInputStream()));
            if (!cilent.isOutputShutdown() && !cilent.isClosed() && cilent.isConnected())
            {
                jbtSubscribe.setFocusable(false);
                String data = null;
                while ((data = reader.readLine()) != null) {
                    logger.info("data is " + data);
                    if (needStop) {
                        return;
                    }

                    JSONObject jsonObject = JSONObject.parseObject(data);
                    RawDataDisplay dataDisplay = new RawDataDisplay();
                    dataDisplay.devNo = jsonObject.get("devNo") == null ? "" : jsonObject.get("devNo").toString();
                    dataDisplay.direction = jsonObject.get("direction") == null ? "" : jsonObject.get("direction").toString();
                    dataDisplay.msgId = jsonObject.get("msgId") == null ? "" : jsonObject.get("msgId").toString();
                    dataDisplay.topic = jsonObject.get("topic") == null ? "" : jsonObject.get("topic").toString();
                    //jsonarray数据
                    String[] object = jsonObject.get("object").toString().replace("[", "").replace("]", "").replace("{", "").replace("}", "").replace("\"\"","\"").split(",");


                    //十六进制的原始数据体
                    StringBuilder resultHex = new StringBuilder();
                    //消息ID
                    String hexNewsid="";
//                if (dataDisplay.direction.equals("down"))
//                {
//
//                }else
                    {
                        Integer[] objectarray = Arrays.stream(object).map(x -> (Math.round(Float.parseFloat(x) + 256) % 256)).toArray(Integer[]::new);


                        for (Integer i : objectarray) {
                            resultHex.append(BitOperator.intToHex(i, 2));
                        }
                        //dataDisplay.arrayobject = JSONArray.parseArray(jsonObject.get("object").toString());


                        hexNewsid = resultHex.substring(2, 6);
                    }


                    //                Integer[] objectarray = Arrays.stream(object).map(x -> (Math.round(Float.parseFloat(x) + 256) % 256)).toArray(Integer[]::new);
//
//                //十六进制的原始数据体
//                String resultHex = "";
//                for (Integer i : objectarray) {
//                    resultHex += BitOperator.intToHex(i, 2);
//                }
//                //dataDisplay.arrayobject = JSONArray.parseArray(jsonObject.get("object").toString());
//
//                //消息ID
//                String hexNewsid = resultHex.substring(2, 6);
                    //dataDisplay.object = jsonObject.get("object").toString();
                    dataDisplay.hostName = jsonObject.get("hostName").toString();
                    dataDisplay.date = jsonObject.get("date").toString();

                    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
                    //判断消息id，是否需要过去指定的消息id
                    //StringBuilder messageid = new StringBuilder();
                    if (jListMessage.getModel().getSize() == 0) {
                        tableModel.addRow(new Object[]{dataDisplay.date, dataDisplay.devNo, hexNewsid, dataDisplay.direction, resultHex.toString(), dataDisplay.hostName,
                                dataDisplay.Remote});
                    } else {
                        for (int i = 0; i < jListMessage.getModel().getSize(); i++) {
                            //messageid.append(jListMessage.getModel().getElementAt(i)).append(",");
                            //会根据筛选的消息id进行数据展示，将包含在筛选内的消息id不显示
                            if (!jListMessage.getModel().getElementAt(i).equals(hexNewsid)) {
                                tableModel.addRow(new Object[]{dataDisplay.date, dataDisplay.devNo, hexNewsid, dataDisplay.direction, resultHex.toString(), dataDisplay.hostName,
                                        dataDisplay.Remote});
                            }
                        }
                    }
                }
            }else
            {
                JOptionPane.showMessageDialog(null,
                        "服务端断开连接！！！",
                        "提示", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            //ex.printStackTrace();
            logger.error("数据解析出错：" + ex.toString());
            JOptionPane.showMessageDialog(null,
                    "数据解析出错:" + ex.toString(),
                    "提示", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (needStop) {
                return;
            }
        }
    }
}

